package com.sc.nft.web;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@Component
@WebFilter(filterName = "LoggingFilter", urlPatterns = "/**")
public class LoggingFilter implements Filter {

    private final String TRACE_HEADER_NAME = "X-Trace-Id";

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        String traceId = request.getHeader(TRACE_HEADER_NAME);
        if (StrUtil.isBlank(traceId)) {
            traceId = IdUtil.simpleUUID();
        }
        try (MDC.MDCCloseable ignore = MDC.putCloseable(TRACE_HEADER_NAME, traceId)) {
            if (log.isDebugEnabled()) {
                log.debug("Request {}, token: {}", request.getRequestURI(), request.getHeader("token"));
            }
            chain.doFilter(req, res);
        }
    }
}
